package com.cqut.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cqut.service.IUserService;
import com.cqut.dao.RoleRigthMapper;
import com.cqut.dao.UserMapper;
import com.cqut.dao.UserMapperExtra;
import com.cqut.dto.LimitShowDTO;
import com.cqut.dto.LoginDTO;
import com.cqut.dto.LoginInfoDTO;
import com.cqut.dto.UserDTO;
import com.cqut.model.User;
import com.cqut.util.SqlUtil;
import com.cqut.util.SystemConstants;
import com.cqut.service.ILoginService;

@Service
public class UserService implements IUserService {
    @Resource(name="userMapper")
    private UserMapper userMapper;
    
    @Resource(name="userMapperExtra")
	private UserMapperExtra userMapperExtra;
    
    @Resource(name="loginService")
	private ILoginService loginService;
    
    @Resource(name="roleRigthMapper")
    private RoleRigthMapper roleRigthMapper;
    
    
    public static final String FLAG_KEY = "repetition"; //用户名或者账号重复返回的字段
	public static final String TRUE_KEY = "true";
	public static final String FALSE_KEY = "false";
    
    /**
     * 新增方法
     */
    @Override
    public boolean save(User user) {
        return userMapper.insert(user) > 0;
    }

    /**
     * 修改
     */
    @Override
    public boolean update(User user) {
        return userMapper.updateByPrimaryKeySelective(user) >= 0;
    }

    /**
     * 删除
     */
    @Override
    public boolean delete(String userId) {
        return userMapper.deleteByPrimaryKey(userId) > 0;
    }

    /**
     * 批量删除
     */
    @Override
    public boolean batchDelete(String[] primaryKeys) {
        return userMapper.deleteByPrimaryKeys(primaryKeys) > 0;
    }

    /**
     * 查看详情
     */
    @Override
    public User findModel(String userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    /**
     * 根据ID查指定数据
     */
    @Override
    public User findModel(String userId, String[] parameters) {
        return userMapper.findModel(userId, SqlUtil.formatParameters(parameters));
    }
 
    /**
     * 列表数据可以重命名列名
     */
    public Map<String, Object> findMap(String userId) {
        String[][] parameters = {{"user_id", "userId"}, {"user_name", "userName"}, {"user_type", "userType"}, {"user_sex", "userSex"}, {"user_no", "userNo"}, {"user_mailbox", "userMailbox"}, {"user_phone", "userPhone"}, {"user_college", "userCollege"}, {"user_password", "userPassword"}};
        return this.findMap(userId, parameters);
    }

    /**
     * 列表数据可查指定的列名
     */
    public Map<String, Object> findMap(String userId, String[][] parameters) {
        return userMapper.findMap(userId, SqlUtil.formatParametersForAlias(parameters));
    }

   
    @Override
    public List<User> loadModels() {
        return this.loadModels(null, null, null, null, -1, -1);
    }

    @Override
    public List<User> loadModels(String condition, Object[] values, String order, String sort, int curPage, int limit) {
        return this.loadModels(null, condition, values, order, sort, curPage, limit);
    }

    @Override
    public List<User> loadModels(String[] parameters, String condition, Object[] values, String order, String sort, int curPage, int limit) {
        return userMapper.loadModels(SqlUtil.formatParameters(parameters), SqlUtil.fillCondition(condition, values), order, sort, SqlUtil.getOffset(curPage, limit), limit);
    }

    @Override
    public List<Map<String, Object>> loadMaps() {
        String[][] parameters = {{"user_id", "userId"}, {"user_name", "userName"}, {"user_type", "userType"}, {"user_sex", "userSex"}, {"user_no", "userNo"}, {"user_mailbox", "userMailbox"}, {"user_phone", "userPhone"}, {"user_college", "userCollege"}, {"user_password", "userPaossword"}};
        return this.loadMaps(parameters, null, null, null, null, -1, -1);
    }

    @Override
    public List<Map<String, Object>> loadMaps(String condition, Object[] values, String order, String sort, int curPage, int limit) {
        String[][] parameters = {{"user_id", "userId"}, {"user_name", "userName"}, {"user_type", "userType"}, {"user_sex", "userSex"}, {"user_no", "userNo"}, {"user_mailbox", "userMailbox"}, {"user_phone", "userPhone"}, {"user_college", "userCollege"}, {"user_password", "userPassword"}};
        return this.loadMaps(parameters, condition, values, order, sort, curPage, limit);
    }

    @Override
    public List<Map<String, Object>> loadMaps(String[][] parameters, String condition, Object[] values, String order, String sort, int curPage, int limit) {
        return userMapper.loadMaps(SqlUtil.formatParametersForAlias(parameters), SqlUtil.fillCondition(condition, values), order, sort, SqlUtil.getOffset(curPage, limit), limit);
    }

    @Override
    public long count() {
        return this.count(null, false);
    }

    @Override
    public long count(String condition, Object[] values) {
        return this.count(null, condition, values, false);
    }

    @Override
    public long count(String[] parameters, boolean isDistinct) {
        return this.count(parameters, null, null, isDistinct);
    }

    @Override
    public long count(String[] parameters, String condition, Object[] values, boolean isDistinct) {
        return userMapper.count(SqlUtil.formatParameters(parameters), SqlUtil.fillCondition(condition, values), isDistinct);
    }

    /**
     * 初始化列表
     */
	@Override
	public List<Map<String, Object>> findUsersWithLimit(UserDTO userDTO,
			LimitShowDTO limitShowDTO) {
		// TODO Auto-generated method stub
		return userMapperExtra.findUserContent();
	}

	@Override
	public Map<String, Object> findUserById(String curUserid) {
		// TODO Auto-generated method stub
		return userMapperExtra.findUserById(curUserid);
	}

	@Override
	public List<Map<String, Object>> searchForUser(UserDTO userDTO, LimitShowDTO limitShowDTO) {
		return userMapperExtra.
				searchForUser(userDTO.getUserType(),userDTO.getUserName(), limitShowDTO.calculateStart(), limitShowDTO.calculateEnd());
	}

	@Override
	public Object findCountOfUsers(UserDTO userDTO) {
		// TODO Auto-generated method stub
		Integer userType = userDTO.getUserType();
		String userName = userDTO.getUserName();

		System.out.println(userDTO.getUserType());
		String count = 
				userMapperExtra.searchForUserNo(userType,userName, -1, -1);
		return count;
	}

	/**
	 * 根据当前登录人的信息修改其密码
	 * */
	@Override
	@Transactional
	public String updatePassword(LoginInfoDTO loginInfoDTO, String password, String oldPassword) {
		
		if (userMapperExtra.judgePassword(loginInfoDTO.getCurUserid(), oldPassword) == null || ((Map<String, Object>) userMapperExtra.judgePassword(loginInfoDTO.getCurUserid(), oldPassword)).size() == 0)
			return "初始密码不正确";
		
		if (userMapperExtra.updatePassword(loginInfoDTO.getCurUserid(), password) > 0)
			return TRUE_KEY;
		
		return FALSE_KEY;
	}
	
	/**
	 * 根据id启用用户
	 * */
	@Override
	public boolean startUserById(String userId) {
		
		return userMapperExtra.startUserById(userId) > 0;
	}
	
	/**
	 * 根据id禁用用户
	 * */
	@Override
	public boolean forbiddenUserById(String userId) {
		
		return userMapperExtra.forbiddenUserById(userId) > 0;
	}
	
	/**
	 * 判断用户名是否重复
	 * */
	@Override
	public boolean duplicateCheckingUserName(String userName) {
		
		return userMapperExtra.duplicateCheckingUserName(userName) == 0;
	}

	/**
	 * 判断账号是否重复
	 * */
	@Override
	public boolean duplicateCheckingUserCode(String userNo) {
		
		return userMapperExtra.duplicateCheckingUserCode(userNo) == 0;
	}
	
	/**
	 * 判断密码是否是初始密码
	 * */
	@Override
	public boolean judgePassword(LoginInfoDTO loginInfoDTO) {
		User user = userMapper.selectByPrimaryKey(loginInfoDTO.getCurUserid());
		
		return user.getUserPassword().equals(SystemConstants.INIT_PASSWORD);
	}
	
	@Override
	public Map<String, Object> getToken(LoginInfoDTO loginInfoDTO) {
		Map<String, Object> info = userMapperExtra.getLoginInfo(loginInfoDTO.getCurUserid());
		
		LoginDTO loginDTO = new LoginDTO();
		loginDTO.setPassword((String) info.get("password"));
		loginDTO.setUserno((String) info.get("userno"));
		
		if (loginInfoDTO.getCurRoleType().equals(SystemConstants.ST_ROLE_TYPE))
			return loginService.loginForStudent(loginDTO);
		
		else if (loginInfoDTO.getCurRoleType().equals(SystemConstants.OP_ROLE_TYPE))
			return loginService.loginForOP(loginDTO);
		
		else if (loginInfoDTO.getCurRoleType().equals(SystemConstants.JD_ROLE_TYPE))
			return loginService.loginForJD(loginDTO);
		
		return null;
	}
	
	/**
	 * 更新用户
	 * */
	@Override
	@Transactional
	public String updateUser(LoginInfoDTO loginInfoDTO, UserDTO userDTO) {
		if (userMapperExtra.judgeRepetition( userDTO.getUserName(), userDTO.getUserNo()) > 0)
			return FLAG_KEY; //根据当前新增用户的用户名或者账号进行查找，如果操作行数大于0表示重复，返回代表重复的字段
		
		if (userMapper.updateByPrimaryKeySelective(userDTO.toUser()) <= 0)
			return FALSE_KEY;
		/*roleRigthMapper.updateByPrimaryKeySelective(userDTO.toUserAssign());*/
			
		return TRUE_KEY;
	}

	@Override
	public List<Map<String, Object>> getRole() {
		// TODO Auto-generated method stub
		return userMapperExtra.getRole();
	}
	
	/**
	 * 删除用户
	 * */
	@Override
	public Map<String, Object> deleteUsers(String[] userIds) {
		Map<String, Object> temp = new HashMap<String, Object>();
		
		int success = userMapperExtra.deleteUsersByIds(userIds); //成功删除的条数
		int fail = userIds.length - success; //删除失败的条数

		temp.put("success", success);
		temp.put("fail", fail);
		
		return temp;
	}         

	/**
	 * 学生用户新增
	 * @param problemManager
	 * @return
	 */
	@Override
    public boolean userAdd(UserDTO userDTO) {
    	String userId = String.valueOf(System.currentTimeMillis());
    	userDTO.setUserId(userId);
    	String userNo = userDTO.getUserNo();
    	String roleId = userDTO.getRoleId();
    	String userPassword = userDTO.getUserPassword();
    	Integer userType = userDTO.getUserType();
    	//用于判断用户账号已存在
    	if(userMapperExtra.duplicateCheckingUserCode(userNo) > 0){
    		return false;
    	}else{
    		return userMapperExtra.addStudent(userId,userNo,roleId,userPassword,userType) > 0;
    	}      
    }
	
}
